<template>
  <div class="domain-management">
    <n-card title="领域管理" :bordered="false" size="small" class="h-full shadow-sm rounded-8px">
      <template #header-extra>
        <n-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-park-outline-add-one />
          </template>
          新增领域
        </n-button>
      </template>

      <!-- 搜索区域 -->
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-input
            v-model:value="searchParams.keyword"
            placeholder="搜索领域名称或描述"
            clearable
            class="w-240px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <icon-park-outline-search class="text-16px" />
            </template>
          </n-input>
          <n-select
            v-model:value="searchParams.is_enabled"
            placeholder="启用状态"
            clearable
            class="w-120px"
            :options="statusOptions"
          />
          <n-select
            v-model:value="searchParams.sort_by"
            placeholder="排序方式"
            class="w-140px"
            :options="sortOptions"
            @update:value="handleSearch"
          />
          <n-button type="primary" @click="handleSearch">搜索</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
      </n-space>

      <!-- 卡片列表 -->
      <div v-if="loading" class="flex justify-center items-center py-32">
        <n-spin size="large" />
      </div>
      <div v-else-if="tableData.length === 0" class="flex flex-col items-center justify-center py-32 text-gray-500">
        <icon-park-outline-folder-open class="text-48px mb-16px" />
        <span class="text-16px">暂无领域数据</span>
      </div>
      <div v-else>
        <n-grid :x-gap="16" :y-gap="16" :cols="3" responsive="screen" item-responsive>
          <n-grid-item v-for="domain in tableData" :key="domain.id" :span="1">
            <n-card hoverable class="domain-card h-full">
              <n-thing content-indented>
                <template #avatar>
                  <n-avatar
                    round
                    size="large"
                    :style="{
                      backgroundColor: domain.is_enabled ? '#18a058' : '#9ca3af',
                      color: 'white'
                    }"
                  >
                    <icon-park-outline-brain v-if="domain.is_enabled" />
                    <icon-park-outline-pause v-else />
                  </n-avatar>
                </template>

                <template #header>
                  <n-space align="center" justify="space-between">
                    <span class="text-16px font-600 text-gray-800">{{ domain.name }}</span>
                    <n-tag :type="domain.is_enabled ? 'success' : 'default'" size="small">
                      {{ domain.is_enabled ? '已启用' : '未启用' }}
                    </n-tag>
                  </n-space>
                </template>

                <template #description>
                  <n-space vertical size="small">
                    <span class="text-12px text-gray-500">ID: {{ domain.id }} 创建时间: {{ formatTime(domain.created_at) }}</span>
                  </n-space>
                </template>

                <div class="domain-content">
                  <n-space vertical size="medium">
                    <!-- 描述信息 -->
                    <div>
                      <div class="text-14px font-500 text-gray-700 mb-8px">描述</div>
                      <div class="text-13px text-gray-600 leading-relaxed">
                        {{ domain.description || '暂无描述' }}
                      </div>
                    </div>



                    <!-- 欢迎语预览 -->
                    <div v-if="domain.welcome_message_1 || domain.welcome_message_2">
                      <div class="text-14px font-500 text-gray-700 mb-8px">欢迎语</div>
                      <n-space vertical size="small">
                        <div v-if="domain.welcome_message_1" class="text-12px text-gray-600 bg-gray-50 p-8px rounded-4px">
                          <span class="text-blue-600 font-500">欢迎语1:</span> {{ domain.welcome_message_1.slice(0, 50) }}{{ domain.welcome_message_1.length > 50 ? '...' : '' }}
                        </div>
                        <div v-if="domain.welcome_message_2" class="text-12px text-gray-600 bg-gray-50 p-8px rounded-4px">
                          <span class="text-green-600 font-500">欢迎语2:</span> {{ domain.welcome_message_2.slice(0, 50) }}{{ domain.welcome_message_2.length > 50 ? '...' : '' }}
                        </div>
                      </n-space>
                    </div>

                    <!-- 前置条件配置 -->
                    <div v-if="domain.precondition_config?.fields?.length">
                      <div class="text-14px font-500 text-gray-700 mb-8px">前置条件</div>
                      <n-space size="small">
                        <n-tag
                          v-for="field in domain.precondition_config.fields.slice(0, 3)"
                          :key="field.name"
                          size="small"
                          type="info"
                        >
                          {{ field.label }}
                        </n-tag>
                        <n-tag
                          v-if="domain.precondition_config.fields.length > 3"
                          size="small"
                          type="default"
                        >
                          +{{ domain.precondition_config.fields.length - 3 }}
                        </n-tag>
                      </n-space>
                    </div>
                  </n-space>
                </div>

                <template #action>
                  <n-space justify="space-between">
                    <n-space size="small">
                      <n-button size="small" type="primary" @click="handleEdit(domain)">
                        <template #icon>
                          <icon-park-outline-edit />
                        </template>
                        编辑
                      </n-button>
                      <n-button size="small" type="error" @click="handleDelete(domain)">
                        <template #icon>
                          <icon-park-outline-delete />
                        </template>
                        删除
                      </n-button>
                    </n-space>
                    <n-space size="small" align="center">
                      <span class="text-12px text-gray-500">专家数量：{{domain.experts?.length || 0}} 权重: {{ domain.sort_order || 0 }}</span>
                    </n-space>
                  </n-space>
                </template>
              </n-thing>
            </n-card>
          </n-grid-item>
        </n-grid>

        <!-- 分页 -->
        <div class="flex justify-center mt-24px">
          <n-pagination
            v-model:page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :item-count="pagination.itemCount"
            :page-sizes="pagination.pageSizes"
            show-size-picker
            show-quick-jumper
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </div>
      </div>
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal
      v-model:show="modalVisible"
      preset="dialog"
      :title="modalTitle"
      style="width: 90vw; max-width: 1400px;"
      :auto-focus="false"
    >
      <n-grid :cols="2" :x-gap="24" responsive="screen" :collapsed-rows="1">
        <!-- 左列：基本信息 -->
        <n-grid-item>
          <n-card size="small" :bordered="false" class="h-full basic-info-card">
            <template #header>
              <n-space align="center">
                <icon-park-outline-info />
                <span>基本信息</span>
              </n-space>
            </template>
            <n-form
              ref="formRef"
              :model="formData"
              :rules="formRules"
              label-placement="top"
              class="pr-12px"
            >
              <n-form-item label="领域名称" path="name">
                <n-input v-model:value="formData.name" placeholder="请输入领域名称" />
              </n-form-item>
              <n-form-item label="描述" path="description">
                <n-input
                  v-model:value="formData.description"
                  type="textarea"
                  placeholder="请输入领域描述"
                  :rows="4"
                />
              </n-form-item>
              <n-form-item label="欢迎语1" path="welcome_message_1">
                <n-input
                  v-model:value="formData.welcome_message_1"
                  type="textarea"
                  placeholder="请输入欢迎语1"
                  :rows="3"
                />
              </n-form-item>
              <n-form-item label="欢迎语2" path="welcome_message_2">
                <n-input
                  v-model:value="formData.welcome_message_2"
                  type="textarea"
                  placeholder="请输入欢迎语2"
                  :rows="3"
                />
              </n-form-item>
              <n-grid :cols="2" :x-gap="12">
                <n-grid-item>
                  <n-form-item label="排序权重" path="sort_order">
                    <n-input-number v-model:value="formData.sort_order" :min="0" placeholder="排序权重" class="w-full" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="启用状态" path="is_enabled">
                    <n-switch v-model:value="formData.is_enabled" />
                  </n-form-item>
                </n-grid-item>
              </n-grid>
            </n-form>
          </n-card>
        </n-grid-item>

        <!-- 右列：前置条件配置 -->
        <n-grid-item>
          <n-card size="small" :bordered="false" class="h-full precondition-config-card">
            <template #header>
              <n-space align="center" justify="space-between">
                <n-space align="center">
                  <icon-park-outline-setting-config />
                  <span>前置条件配置</span>
                </n-space>
                <n-tag size="small" type="info" v-if="formData.precondition_config?.fields?.length">
                  {{ formData.precondition_config.fields.length }} 个字段
                </n-tag>
              </n-space>
            </template>
            <n-tabs type="line" default-value="visual" class="precondition-tabs">
              <n-tab-pane name="visual" tab="可视化编辑">
                <div class="precondition-editor-container">
                  <PreconditionEditor
                    v-model="formData.precondition_config"
                    @update:model-value="onPreconditionConfigChange"
                  />
                </div>
              </n-tab-pane>
              <n-tab-pane name="json" tab="JSON编辑">
                <div class="json-editor-container">
                  <n-input
                    v-model:value="preconditionConfigStr"
                    type="textarea"
                    placeholder="请输入JSON格式的前置条件配置"
                    :rows="12"
                    @blur="onJsonConfigChange"
                  />
                  <div class="text-12px text-gray-500 mt-8px">
                    <n-alert type="info" size="small" :show-icon="false">
                      <template #header>
                        <span class="text-12px">JSON格式示例</span>
                      </template>
                      <n-code
                        :code='`{"fields": [{"name": "age", "label": "年龄", "type": "number", "required": true}]}`'
                        language="json"
                        :word-wrap="true"
                        class="text-11px"
                      />
                    </n-alert>
                  </div>
                </div>
              </n-tab-pane>
            </n-tabs>
          </n-card>
        </n-grid-item>
      </n-grid>
      <template #action>
        <n-space>
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 高危删除确认弹窗 -->
    <DangerousActionConfirm
      v-model:visible="deleteConfirmVisible"
      :title="`删除领域: ${currentDeleteItem?.name || ''}`"
      :description="deleteDescription"
      :item-info="deleteItemInfo"
      :risks="deleteRisks"
      @confirm="handleConfirmDelete"
      @cancel="handleCancelDelete"
      ref="deleteConfirmRef"
      :disabled="currentDeleteItem?.experts?.length > 0"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { domainApi } from '@/service/api/bizhi'
import { filterApiParams, filterFormData } from '@/utils/api'
import { formatTime } from '@/utils/time'
import PreconditionEditor from '@/components/PreconditionEditor.vue'
import DangerousActionConfirm from '@/components/DangerousActionConfirm.vue'
import { deepClone } from '@/utils/common'

// 类型定义
interface DomainItem {
  id: number
  name: string
  description?: string
  welcome_message_1?: string
  welcome_message_2?: string
  precondition_config?: {
    fields?: Array<{
      name: string
      label: string
      type: string
      required?: boolean
      options?: string[]
    }>
  }
  sort_order?: number
  is_enabled: boolean
  experts?: any[]
  created_at: string
}

const message = useMessage()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const modalVisible = ref(false)
const tableData = ref<DomainItem[]>([])
const formRef = ref()
const preconditionConfigStr = ref('')

// 删除确认相关
const deleteConfirmVisible = ref(false)
const deleteConfirmRef = ref()
const currentDeleteItem = ref<DomainItem | null>(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  is_enabled: null,
  sort_by: 'weight',
  page: 1,
  limit: 20
})

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  description: '',
  welcome_message_1: '',
  welcome_message_2: '',
  precondition_config: null,
  sort_order: 0,
  is_enabled: true
})

// 删除确认相关计算属性
const deleteItemInfo = computed(() => {
  if (!currentDeleteItem.value) return {}
  const item = currentDeleteItem.value
  return {
    'ID': item.id,
    '领域名称': item.name,
    '描述': item.description || '-',
    '专家数量': item.experts?.length || 0,
    '启用状态': item.is_enabled ? '启用' : '未启用',
    '排序权重': item.sort_order || 0,
    '创建时间': formatTime(item.created_at)
  }
})

const deleteRisks = computed(() => {
  const expertCount = currentDeleteItem.value?.experts?.length || 0
  const risks = [
    '删除后该领域将无法恢复',
    '所有相关的问答记录将失去领域关联',
    '相关的统计数据将受到影响'
  ]

  // 如果该领域下有专家，添加特殊提示
  if (expertCount > 0) {
    risks.unshift(`该领域下还有 ${expertCount} 个专家，无法删除`)
    risks.push('请先删除或转移该领域下的所有专家')
  } else {
    risks.push('确认该领域下没有专家后才能删除')
  }

  return risks
})

const deleteDescription = computed(() => {
  const domainName = currentDeleteItem.value?.name || ''
  const expertCount = currentDeleteItem.value?.experts?.length || 0

  if (expertCount > 0) {
    return `您即将删除领域「${domainName}」。注意：该领域下还有 ${expertCount} 个专家，根据系统规则，必须先删除或转移所有专家后才能删除领域。`
  } else {
    return `您即将删除领域「${domainName}」。该领域下没有专家，可以安全删除。删除后该领域的所有相关数据将无法恢复。`
  }
})

// 状态选项
const statusOptions = [
  { label: '启用', value: true },
  { label: '禁用', value: false }
]

// 排序选项
const sortOptions = [
  { label: '按权重', value: 'weight' },
  { label: '按更新时间', value: 'updated_at' }
]

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入领域名称', trigger: 'blur' },
    { max: 100, message: '领域名称不能超过100个字符', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
})

// 弹窗标题
const modalTitle = computed(() => {
  return formData.id ? '编辑领域' : '新增领域'
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await domainApi.getDomainList(filterApiParams(searchParams)) as any
    tableData.value = response.data.list || []
    pagination.itemCount = response.data.pagination?.total || 0
  } catch (error) {
    console.error('获取领域数据失败:', error)
    message.error('获取数据失败')
    tableData.value = []
    pagination.itemCount = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchParams, {
    keyword: '',
    is_enabled: null,
    sort_by: 'weight',
    page: 1,
    limit: 20
  })
  fetchData()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  searchParams.page = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  searchParams.limit = pageSize
  searchParams.page = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  // 重置为初始状态
  Object.assign(formData, {
    id: null,
    name: '',
    description: '',
    welcome_message_1: '',
    welcome_message_2: '',
    precondition_config: null,
    sort_order: 0,
    is_enabled: true
  })
  preconditionConfigStr.value = ''
  modalVisible.value = true
}

// 编辑
const handleEdit = (row: DomainItem) => {
  // 使用深拷贝确保不会修改原始数据
  const clonedRow = deepClone(row)
  Object.assign(formData, clonedRow)

  preconditionConfigStr.value = row.precondition_config
    ? JSON.stringify(row.precondition_config, null, 2)
    : ''
  modalVisible.value = true
}

// 可视化编辑器配置变化
const onPreconditionConfigChange = (value: any) => {
  // 同步更新JSON字符串
  preconditionConfigStr.value = value ? JSON.stringify(value, null, 2) : ''
}

// JSON编辑器配置变化
const onJsonConfigChange = () => {
  try {
    if (preconditionConfigStr.value.trim()) {
      const parsed = JSON.parse(preconditionConfigStr.value)
      formData.precondition_config = parsed
    } else {
      formData.precondition_config = null
    }
  } catch (error) {
    // JSON格式错误时提示用户
    console.warn('JSON格式错误:', error)
    message.error('JSON格式错误，请检查语法')
    // 不更新可视化编辑器
  }
}

// 删除 - 显示高危确认弹窗
const handleDelete = (row: DomainItem) => {
  currentDeleteItem.value = row
  deleteConfirmVisible.value = true
}

// 确认删除
const handleConfirmDelete = async (password: string) => {
  try {
    // 这里应该调用API验证管理员密码
    // 暂时模拟验证逻辑
    if (password.length < 6) {
      message.error('密码长度不能少于6位')
      return
    }

    // 执行删除操作
    if (!currentDeleteItem.value) {
      message.error('删除项目不存在')
      return
    }

    // 检查是否有专家，前端再次验证
    if (currentDeleteItem.value.experts?.length > 0) {
      message.error('该领域下还有专家，无法删除')
      return
    }

    const result = await domainApi.deleteDomain(currentDeleteItem.value.id, password) as any

    // 检查Alova返回的结果
    if (result && !result.isSuccess) {
      // 这是业务逻辑错误（如API返回code: 400）
      let errorMessage = result.message || '删除失败，请重试'

      console.error('删除业务逻辑错误:', result)
      message.error(errorMessage)
      return // 不关闭弹窗，让用户可以重试
    }

    // 只有真正成功才会执行到这里
    message.success('删除成功！！！！')
    deleteConfirmVisible.value = false
    currentDeleteItem.value = null
    fetchData()
  } catch (error) {
    console.error('删除网络异常:', error)

    // 这里只处理真正的网络异常（网络错误、超时等）
    let errorMessage = '网络错误，请检查网络连接后重试'

    if (error?.message) {
      errorMessage = error.message
    }

    message.error(errorMessage)

    // 网络异常时不关闭弹窗，让用户可以重试
  } finally {
    deleteConfirmRef.value?.setLoading(false)
  }
}

// 取消删除
const handleCancelDelete = () => {
  currentDeleteItem.value = null
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()

    // 验证前置条件配置
    if (formData.precondition_config) {
      const config = formData.precondition_config
      if (config.fields && Array.isArray(config.fields)) {
        // 验证字段配置
        for (const field of config.fields) {
          if (!field.name || !field.label || !field.type) {
            message.error('前置条件配置不完整，请检查字段名称、标签和类型')
            return
          }
          
          // 验证字段名称格式
          const nameRegex = /^[a-zA-Z0-9_]+$/
          if (!nameRegex.test(field.name)) {
            message.error(`字段"${field.label}"的名称格式不正确，只能包含英文字母、数字和下划线`)
            return
          }
          
          // 验证字段名称唯一性
          const fieldNames = config.fields.map(f => f.name)
          const duplicateIndex = fieldNames.indexOf(field.name)
          if (duplicateIndex !== fieldNames.lastIndexOf(field.name)) {
            message.error(`字段名称"${field.name}"重复，请修改`)
            return
          }
          
          if ((field.type === 'radio' || field.type === 'checkbox') && (!field.options || field.options.length === 0)) {
            message.error(`${field.type === 'radio' ? '单选框' : '多选框'}类型字段必须配置选项`)
            return
          }
        }
      }
    }

    submitLoading.value = true

    // 过滤掉null值的表单数据
    const filteredData = filterFormData(formData)

    if (formData.id) {
      await domainApi.updateDomain(formData.id, filteredData)
      message.success('更新成功')
    } else {
      await domainApi.createDomain(filteredData)
      message.success('创建成功')
    }

    modalVisible.value = false
    fetchData()
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.precondition-tabs {
  height: 100%;
}

.precondition-tabs :deep(.n-tabs-content) {
  height: calc(100% - 40px);
  overflow: hidden;
}

.precondition-editor-container {
  height: 800px;
  overflow-y: auto;
  padding-right: 8px;
}

.json-editor-container {
  height: 800px;
  display: flex;
  flex-direction: column;
}

.json-editor-container .n-input {
  flex: 1;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .precondition-editor-container,
  .json-editor-container {
    height: 400px;
  }
}

@media (max-width: 1200px) {
  .precondition-editor-container,
  .json-editor-container {
    height: 350px;
  }

  .n-card :deep(.n-card__content) {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .precondition-editor-container,
  .json-editor-container {
    height: 300px;
  }

  .n-card :deep(.n-card__content) {
    padding: 12px;
  }

  .n-card :deep(.n-card__header) {
    padding: 12px;
  }
}

/* 优化卡片样式 */
.n-card {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.n-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.n-card :deep(.n-card__content) {
  padding: 20px;
}

.n-card :deep(.n-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

/* 基本信息卡片 */
.basic-info-card {
  background: linear-gradient(135deg, #eaeeee 0%, #fff 100%);
}

.basic-info-card :deep(.n-card__header) {
  background: rgba(24, 160, 88, 0.05);
  color: #18a058;
}

/* 前置条件配置卡片 */
.precondition-config-card {
  background: linear-gradient(135deg, #f0fff5 0%, #fff 100%);
}

.precondition-config-card :deep(.n-card__header) {
  background: rgba(51, 54, 57, 0.05);
  color: #333639;
}

/* 优化表单布局 */
.n-form-item {
  margin-bottom: 16px;
}

.n-form-item:last-child {
  margin-bottom: 0;
}

/* 优化标签显示 */
.n-tag {
  font-weight: 500;
}

/* 页面容器 */
.domain-management {
  height: 100%;
}

/* 卡片样式 */
.domain-card {
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.domain-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: #d9d9d9;
}

.domain-content {
  margin-top: 12px;
}

.domain-content .n-statistic {
  text-align: center;
}

.domain-content .n-statistic :deep(.n-statistic-label) {
  font-size: 12px;
  color: #666;
}

.domain-content .n-statistic :deep(.n-statistic-value) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .domain-management :deep(.n-grid) {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}

@media (max-width: 768px) {
  .domain-management :deep(.n-grid) {
    grid-template-columns: 1fr !important;
  }

  .domain-content {
    margin-top: 8px;
  }

  .domain-content .n-space {
    gap: 8px !important;
  }

  .domain-card .n-thing :deep(.n-thing-header) {
    margin-bottom: 8px;
  }

  .domain-card .n-thing :deep(.n-thing-main) {
    margin-left: 0;
    margin-top: 8px;
  }
}
</style>
